/*
 * Copyright (c) 2021
 * User:LENOVO
 * File:无重复字符的最长子串.java
 * Date:2021/02/18 14:15:18
 */

package org.bytedance.字符串;

import java.util.HashMap;
import java.util.Map;

/**
 * 给定一个字符串，请你找出其中不含有重复字符的 最长子串 的长度。
 */
public class 无重复字符的最长子串 {

    public static void main(String[] args) {
        无重复字符的最长子串 instance = new 无重复字符的最长子串();
        String s = "abcabcbb";
        int i = instance.lengthOfLongestSubstring(s);
        System.out.println(i);
        s = "bbbbb";
        i = instance.lengthOfLongestSubstring(s);
        System.out.println(i);

        s = "pwwkew";
        i = instance.lengthOfLongestSubstring(s);
        System.out.println(i);


        s = "";
        i = instance.lengthOfLongestSubstring(s);
        System.out.println(i);

    }


    public int lengthOfLongestSubstring(String s) {
        if (null == s) return 0;
        if (s.length() <= 1) return s.length();
        Map<Character, Integer> map = new HashMap<>();
        int left = 0, right = 0;
        int res = 0;
        while (right < s.length()) {
            char c = s.charAt(right);
            right++;
            if (map.containsKey(c)) {
                map.put(c, map.get(c) + 1);
            } else {
                map.put(c, 1);
            }
            while (map.get(c) > 1) {
                char d = s.charAt(left);
                left++;
                if (map.containsKey(d)) {
                    map.put(d, map.get(d) - 1);
                }
            }
            res = Math.max(res, right - left);
        }
        return res;
    }
}
